package com.example.demo.controller;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import com.example.demo.dto.PageExtra;
import com.example.demo.dto.UserDTO;
import com.example.demo.request.CreateUserRequest;
import com.example.demo.request.UpdateUserRequest;
import com.example.demo.request.ChangePasswordRequest;
import com.example.demo.response.ApiResponse;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.Map;
import java.util.List;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;



@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;


    @GetMapping
    public ResponseEntity<ApiResponse<List<UserDTO>>> getUsers(
             @RequestParam(defaultValue = "0") int page,
             @RequestParam(defaultValue = "10") int size,
            HttpServletRequest request) {

        List<UserDTO> users = userService.getUsers(page, size);
        long total = userService.countUsers();
        PageExtra extra = new PageExtra(page, size, total);

        return ResponseEntity.ok(
                ApiResponse.success(users, "请求成功", request.getRequestURI(), extra)
        );
    }


    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<UserDTO>> getUser(
             @PathVariable Integer id,
            HttpServletRequest request) {

        UserDTO user = userService.getUserById(id);
        return ResponseEntity.ok(
                ApiResponse.success(user, "查询成功", request.getRequestURI(), null)
        );
    }

    @PostMapping
    public ResponseEntity<ApiResponse<UserDTO>> createUser(
            @Valid @RequestBody CreateUserRequest request,
            HttpServletRequest requestObj) {

        com.example.demo.entity.User user = userService.createUser(request);
        UserDTO dto = UserDTO.fromEntity(user);
        return ResponseEntity.status(201).body(
                ApiResponse.created(dto, "用户创建成功", requestObj.getRequestURI())
        );
    }


    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<UserDTO>> updateUser(
            @PathVariable Integer id,
            @Valid @RequestBody UpdateUserRequest request,
            HttpServletRequest requestObj) {

        userService.updateUser(id, request);
        UserDTO user = userService.getUserById(id);
        return ResponseEntity.ok(
                ApiResponse.success(user, "用户更新成功", requestObj.getRequestURI(), null)
        );
    }


    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteUser(
            @PathVariable Integer id,
            HttpServletRequest requestObj) {

        userService.deleteUser(id);
        return ResponseEntity.ok(
                ApiResponse.success(null, "用户删除成功", requestObj.getRequestURI(), null)
        );
    }
    

    @GetMapping("/search")
    public ResponseEntity<ApiResponse<List<UserDTO>>> searchUsers(
            @RequestParam String name,
            HttpServletRequest request) {
        
        List<UserDTO> users = userService.searchUsersByName(name);
        return ResponseEntity.ok(
                ApiResponse.success(users, "搜索成功", request.getRequestURI(), null)
        );
    }
    

    @GetMapping("/department/{deptId}")
    public ResponseEntity<ApiResponse<List<UserDTO>>> getUsersByDeptId(
             @PathVariable Integer deptId,
            HttpServletRequest request) {

        List<UserDTO> users = userService.getUsersByDeptId(deptId);
        return ResponseEntity.ok(
                ApiResponse.success(users, "查询成功", request.getRequestURI(), null)
        );
    }



    @PostMapping("/batch-import")
    public ResponseEntity<ApiResponse<Map<String, Object>>> batchImportUsers(

            @RequestParam("file") MultipartFile file,
            HttpServletRequest request) {

        Map<String, Object> result = userService.batchImportUsers(file);

        if (Boolean.TRUE.equals(result.get("success"))) {
            return ResponseEntity.ok(
                ApiResponse.success(result, "批量导入成功", request.getRequestURI(), null)
            );
        } else {
            return ResponseEntity.badRequest().body(
                ApiResponse.error(result.get("message").toString(), request.getRequestURI())
            );
        }
    }


    @GetMapping("/batch-export")
    public ResponseEntity<byte[]> batchExportUsers() {
        try {
            byte[] excelData = userService.batchExportUsers();
            
            // 生成文件名（包含时间戳）
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
            String filename = "users_export_" + timestamp + ".xlsx";
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", filename);
            headers.setContentLength(excelData.length);
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(excelData);
        } catch (Exception e) {
            // 如果导出失败，返回错误信息
            return ResponseEntity.internalServerError().build();
        }
    }


    @PutMapping("/change-password")
    public ResponseEntity<ApiResponse<Void>> changePassword(
            @Valid @RequestBody ChangePasswordRequest request,
            HttpServletRequest requestObj) {
        
        try {
            userService.changePassword(request.getUserId(), request.getOldPassword(), request.getNewPassword());
            return ResponseEntity.ok(
                    ApiResponse.success(null, "密码修改成功", requestObj.getRequestURI(), null)
            );
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(
                    ApiResponse.error(e.getMessage(), requestObj.getRequestURI())
            );
        }
    }
}